<template>
  <view class="message-container">
    <!-- 自定义header -->
    <CustomHeader></CustomHeader>
    <view class="header">
      <view class="header-content">
        <text class="header-title">消息</text>
      </view>
    </view>
    
    <!-- 消息列表 -->
    <scroll-view class="message-list" scroll-y>
      <!-- 会话列表 -->
      <view
        class="message-item"
        v-for="item in sessionList"
        :key="item.id"
        @tap="goToChat(item)"
      >
        <!-- 头像 -->
        <view class="avatar-wrapper">
          <image
            class="avatar"
            :src="item.otherUserInfo.face || '/static/images/avatar.png'"
          />
          <!-- 未读消息标记 -->
          <view 
            v-if="item.otherUserInfo.unreadMsgCount > 0" 
            class="unread-badge"
          >
            <text class="unread-count">
              {{ item.otherUserInfo.unreadMsgCount > 99 ? '99+' : item.otherUserInfo.unreadMsgCount }}
            </text>
          </view>
        </view>
        
        <!-- 消息内容 -->
        <view class="content">
          <view class="top-line">
            <text class="name">{{ item.otherUserInfo.name }}</text>
            <text class="time" v-if="item.lastMsgTime">
              {{ formatTime(item.lastMsgTime) }}
            </text>
          </view>
          <view class="last-msg">
            <text class="msg-text">
              {{ item.lastMessage || '暂无消息' }}
            </text>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="sessionList.length === 0 && !loading" class="empty-state">
        <image src="/static/icons/msg/msg-info.png" class="empty-icon" />
        <text class="empty-text">暂无消息</text>
      </view>
      
      <!-- 加载中 -->
      <view v-if="loading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>
    </scroll-view>
  </view>
  <CustomTabBar :currentIndex="2" />
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import CustomTabBar from '@/components/CustomTabBar.vue';
import CustomHeader from '@/components/CustomHeader.vue';
import { useSessionStore } from '@/stores/modules/session';
import { useUserStore } from '@/stores/modules/user';

const userStore = useUserStore();
const sessionStore = useSessionStore();

// 从 store 获取会话列表
const sessionList = computed(() => sessionStore.sessionList);
const loading = ref(false);

// 刷新会话列表
const refreshSessionList = async () => {
  loading.value = true;
  try {
    console.log("刷新会话列表...");
    await sessionStore.fetchSessionList();
    console.log("会话列表刷新成功");
  } catch (error) {
    console.error("刷新会话列表失败:", error);
    uni.showToast({
      title: "刷新失败",
      icon: "none",
      duration: 2000
    });
  } finally {
    loading.value = false;
  }
};

// 格式化时间显示
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  
  const now = new Date();
  const msgTime = new Date(timestamp);
  const diff = now - msgTime;
  
  // 一分钟内
  if (diff < 60000) {
    return '刚刚';
  }
  
  // 一小时内
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`;
  }
  
  // 今天
  if (now.toDateString() === msgTime.toDateString()) {
    const hours = msgTime.getHours().toString().padStart(2, '0');
    const minutes = msgTime.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  }
  
  // 昨天
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  if (yesterday.toDateString() === msgTime.toDateString()) {
    return '昨天';
  }
  
  // 一周内
  if (diff < 7 * 24 * 3600000) {
    return `${Math.floor(diff / (24 * 3600000))}天前`;
  }
  
  // 超过一周，显示具体日期
  const month = (msgTime.getMonth() + 1).toString().padStart(2, '0');
  const day = msgTime.getDate().toString().padStart(2, '0');
  return `${month}-${day}`;
};

// 跳转到聊天页面
const goToChat = (item) => {
  console.log("跳转到聊天页面，会话信息:", item);
  
  // HR跳转到HR聊天页面
  uni.navigateTo({
    url: `/pages/company/chat?sessionId=${item.id}&name=${encodeURIComponent(item.otherUserInfo.name)}&candidateId=${item.otherUserInfo.id}`
  });
};

// 页面加载时
onMounted(() => {
  console.log("消息页面加载，会话列表数量:", sessionList.value.length);
  
  // 如果本地没有数据，则刷新
  if (sessionList.value.length === 0) {
    refreshSessionList();
  }
});
</script>

<style lang="scss" scoped>
.message-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 自定义header样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 30rpx;
  height: 88rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
}

.message-list {
  height: calc(100vh - 176rpx); /* 减去header和tabbar高度 */
}

.message-item {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  transition: background-color 0.2s;

  &:active {
    background-color: #f8f8f8;
  }
}

/* 头像 */
.avatar-wrapper {
  position: relative;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
}

.unread-badge {
  position: absolute;
  top: -4rpx;
  right: -4rpx;
  background-color: #ff4757;
  border-radius: 20rpx;
  padding: 4rpx 8rpx;
  min-width: 32rpx;
  height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid #fff;
}

.unread-count {
  font-size: 20rpx;
  color: #fff;
  font-weight: 500;
  transform: scale(0.9);
}

/* 消息内容 */
.content {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
}

.top-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
}

.time {
  font-size: 24rpx;
  color: #999;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
  flex-shrink: 0;
  margin-left: 20rpx;
}

.last-msg {
  .msg-text {
    font-size: 28rpx;
    color: #999;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
      "Helvetica Neue", Arial, sans-serif;
  }
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;

  .empty-icon {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 20rpx;
    opacity: 0.5;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
      "Helvetica Neue", Arial, sans-serif;
  }
}

/* 加载中状态 */
.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200rpx;

  .loading-text {
    font-size: 28rpx;
    color: #999;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
      "Helvetica Neue", Arial, sans-serif;
  }
}
</style>
